﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace OracleCompare
{
    public partial class Form3 : Form
    {
        public byte type;
        public List<TableCol> col;
        private List<Dictionary<string, string>> list;
        private string[] allSql;

        public Form3()
        {
            InitializeComponent();
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            switch (type)
            {
                case (byte)TableType.Source:
                case (byte)TableType.Target:
                case (byte)TableType.Same:
                    InitTable();
                    break;
                case (byte)TableType.Different:
                    list = Configs.DifferentList;
                    if (!list.Any()) { this.Close(); return; }
                    var keys = col.Where(m => m.IsKey).Select(m => m.ColumnName).Distinct();
                    if (!keys.Any()) { this.Close(); return; }
                    foreach (var c in col)
                    {
                        dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()
                        {
                            HeaderText = (keys.Contains(c.ColumnName) ? "" : "源：") + c.ColumnName,
                            Name = c.ColumnName,
                            ReadOnly = true,
                            SortMode = DataGridViewColumnSortMode.NotSortable
                        });
                        if (!keys.Contains(c.ColumnName))
                        {
                            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()
                            {
                                HeaderText = "目标：" + c.ColumnName,
                                Name = "t" + c.ColumnName,
                                ReadOnly = true,
                                SortMode = DataGridViewColumnSortMode.NotSortable
                            });
                        }
                    }
                    dataGridView1.Columns.Add(new DataGridViewButtonColumn()
                    {
                        ReadOnly = true,
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    });
                    string tableName = col.Select(m => m.TableName).First();
                    List<string> sql = new List<string>();
                    foreach (var l in list)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append(string.Format("UPDATE \"{0}\" SET ", tableName));
                        List<string> updateL = new List<string>();
                        List<string> whereL = new List<string>();

                        List<string> array = new List<string>();
                        foreach (var c in col)
                        {
                            array.Add(l[c.ColumnName]);
                            string s = string.Format("\"{0}\" = ", c.ColumnName);
                            if (c.DataType.Contains("DATE"))
                            {
                                s += string.Format("TO_DATE('{0}', 'YYYY/MM/DD HH24:MI:SS')", l[c.ColumnName]);
                            }
                            else
                            {
                                s += string.Format("'{0}'", l[c.ColumnName].Replace("'", "''"));
                            }
                            if (c.IsKey)
                            {
                                whereL.Add(s);
                            }
                            else
                            {
                                array.Add(l["t" + c.ColumnName]);
                                if (l[c.ColumnName] != l["t" + c.ColumnName]) updateL.Add(s);
                            }
                        }
                        array.Add("查看更新sql");
                        sb.Append(string.Join(",", updateL));
                        sb.Append(" WHERE ");
                        sb.Append(string.Join(" AND ", whereL));
                        sql.Add(sb.ToString());
                        dataGridView1.Rows.Add(array.ToArray());
                    }
                    allSql = sql.ToArray();
                    break;
            }
        }

        private void InitTable()
        {
            string btn = "";
            switch (type)
            {
                case (byte)TableType.Source:
                    list = Configs.SourceList;
                    btn = "插入";
                    break;
                case (byte)TableType.Target:
                    list = Configs.TargetList;
                    btn = "删除";
                    break;
                case (byte)TableType.Same:
                    list = Configs.SameList;
                    break;
                default:
                    list = new List<Dictionary<string, string>>();
                    break;
            }
            if (!list.Any()) { this.Close(); return; }
            foreach (var c in col)
            {
                dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()
                {
                    HeaderText = c.ColumnName,
                    Name = c.ColumnName,
                    ReadOnly = true,
                    SortMode = DataGridViewColumnSortMode.NotSortable
                });
            }
            if (!string.IsNullOrEmpty(btn))
            {
                dataGridView1.Columns.Add(new DataGridViewButtonColumn()
                {
                    ReadOnly = true,
                    SortMode = DataGridViewColumnSortMode.NotSortable
                });
            }
            string tableName = col.Select(m => m.TableName).First();
            List<string> addSqls = new List<string>();
            List<string> delSqls = new List<string>();
            foreach (var l in list)
            {
                StringBuilder addSB = new StringBuilder();
                addSB.Append(string.Format("INSERT INTO \"{0}\" VALUES (", tableName));
                List<string> addL = new List<string>();

                StringBuilder delSB = new StringBuilder();
                delSB.Append(string.Format("DELETE FROM \"{0}\" WHERE ", tableName));
                List<string> delL = new List<string>();

                List<string> array = new List<string>();
                foreach (var c in col)
                {
                    array.Add(l[c.ColumnName]);
                    if (c.DataType.Contains("DATE"))
                    {
                        if (!string.IsNullOrEmpty(l[c.ColumnName]))
                        {
                            addL.Add(string.Format("TO_DATE('{0}', 'YYYY/MM/DD HH24:MI:SS')", l[c.ColumnName]));
                            delL.Add(string.Format("\"{0}\" = TO_DATE('{1}', 'YYYY/MM/DD HH24:MI:SS')", c.ColumnName, l[c.ColumnName]));
                        }
                        else
                        {
                            addL.Add("''");
                        }
                    }
                    else
                    {
                        addL.Add(string.Format("'{0}'", l[c.ColumnName].Replace("'", "''")));
                        if (!string.IsNullOrEmpty(l[c.ColumnName]))
                            delL.Add(string.Format("\"{0}\" = '{1}'", c.ColumnName, l[c.ColumnName].Replace("'", "''")));
                    }
                }
                if (!string.IsNullOrEmpty(btn))
                {
                    array.Add("查看" + btn + "sql");
                    addSB.Append(string.Join(",", addL.ToArray()));
                    addSB.Append(")");
                    addSqls.Add(addSB.ToString());
                    delSB.Append(string.Join(" AND ", delL.ToArray()));
                    delSqls.Add(delSB.ToString());
                }
                dataGridView1.Rows.Add(array.ToArray());
            }
            if (!string.IsNullOrEmpty(btn))
            {
                switch (type)
                {
                    case (byte)TableType.Source:
                        allSql = addSqls.ToArray();
                        break;
                    case (byte)TableType.Target:
                        allSql = delSqls.ToArray();
                        break;
                }
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
            if (column is DataGridViewButtonColumn)
            {
                MessageText mt = new MessageText();
                mt.msg = allSql[e.RowIndex];
                mt.ShowDialog();
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
            if (column is DataGridViewTextBoxColumn)
            {
                switch (type)
                {
                    case (byte)TableType.Source:
                    case (byte)TableType.Target:
                    case (byte)TableType.Different:
                        MessageText mt = new MessageText();
                        mt.msg = string.Join(";\r\n\r\n", allSql) + ";";
                        mt.ShowDialog();
                        break;
                }
            }
        }
    }
}